package com.demo.rsa;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.jupiter.api.Test;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
public class RsaTest {
    @Test
    public void t01() throws NoSuchAlgorithmException {
        RSA rsa = new RSA();

        //获得私钥
        rsa.getPrivateKey();
        rsa.getPrivateKeyBase64();
        //获得公钥
        rsa.getPublicKey();
        rsa.getPublicKeyBase64();
        String data = RandomUtil.randomString(128);

        for (int i = 0; i < 10; i++) {
            StopWatch watch = StopWatch.createStarted();
            // ====================== 公钥加密，私钥解密
            byte[] encrypt = rsa.encrypt(StrUtil.bytes(data, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
            System.out.println("加密time: " + watch.getTime(TimeUnit.MILLISECONDS) + " ms");

            watch = StopWatch.createStarted();
            byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
            System.out.println("解密time: " + watch.getTime(TimeUnit.MILLISECONDS) + " ms");
            System.out.println(StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8));

            watch = StopWatch.createStarted();

            // ====================== 私钥加密，公钥解密
            byte[] encrypt2 = rsa.encrypt(StrUtil.bytes(data, CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);
            System.out.println("加密time: " + watch.getTime(TimeUnit.MILLISECONDS) + " ms");

            watch = StopWatch.createStarted();
            byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
            System.out.println("解密time: " + watch.getTime(TimeUnit.MILLISECONDS) + " ms");
            System.out.println(StrUtil.str(decrypt2, CharsetUtil.CHARSET_UTF_8));
        }
    }
}
